<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>胖乖生活取Token</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.7/axios.js"></script>
  </head>
  <body>
    <div class="container">
      <h2>胖乖生活取Token</h2>
      <label for="phoneInput">手机号:</label>
      <input type="text" id="phoneInput" name="phone" />
      <label for="verifyInput">验证码:</label>
      <input type="text" id="verifyInput" name="verify" />
      <div class="button-container">
        <label for="scriptSelector"></label
        ><select id="scriptSelector" onchange="loadScript()" class="spacing">
          <option value="">请选择</option>
          <option value="h5">网页端</option>
          <option value="app">App端</option>
        </select>
        <button onclick="sendPostRequest()" class="spacing">发送验证码</button>
        <button onclick="verifyCode()" class="spacing">登录</button>
      </div>
      <div id="responseDisplay"></div>
      <div class="center-container">
        <button onclick="copy()">复制Token</button>
      </div>
    </div>
    <script>
      const API_SEND_CODE = 'https://userapi.qiekj.com/common/sms/sendCode'
      const API_USER_REG = 'https://userapi.qiekj.com/user/reg'
      let timer = null
      const axiosHeaders = {
        Version: '1.50.0',
        phoneBrand: 'Windows',
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        Connection: 'Keep-Alive',
        'Accept-Encoding': 'gzip',
      }
      function validatePhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/
        return phoneRegex.test(phone)
      }
      async function sendPostRequest() {
        const phoneInput = document.getElementById('phoneInput').value
        if (!validatePhone(phoneInput)) {
          alert('请输入有效的手机号码！')
          return
        }

        if (timer) {
          alert('请等待60秒后再尝试发送验证码')
          return
        }

        try {
          const body = new URLSearchParams({phone: phoneInput, template: 'reg'})
          const response = await axios.post(API_SEND_CODE, body.toString(), {
            headers: axiosHeaders,
          })
          if (response.data.code === 0) {
            alert('验证码发送成功！')
            startTimer()
          } else {
            alert('验证码发送失败：' + response.data.msg)
          }
        } catch (error) {
          console.error('请求失败:', error)
          alert('验证码发送失败！')
        }
      }
      function loadScript() {
        const selector = document.getElementById('scriptSelector')
        const choice = selector.value

        if (choice === 'app') {
          const proceed = window.confirm('App端会掉登录，是否继续？')
          if (!proceed) {
            return
          }
        }

        const script = document.createElement('script')

        const oldScript = document.querySelector(
          'body script[src*=".js"]:not([src*="axios"])'
        )
        if (oldScript) {
          document.body.removeChild(oldScript)
        }

        document.body.appendChild(script)
      }
      // const API_SEND_CODE = 'https://userapi.qiekj.com/common/sms/sendCode'
      // Remove the duplicate declaration of 'API_USER_REG'
      // const API_USER_REG = 'https://userapi.qiekj.com/user/reg'

      function validatePhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/
        return phoneRegex.test(phone)
      }

      // let timer = null

      function UA() {
        const androidVersions = ['8.0', '9.0', '10', '11', '12', '13', '14']
        const phoneModels = [
          'Samsung Galaxy S10',
          'Google Pixel 5',
          'OnePlus 8T',
          'Xiaomi Mi 11',
          'Huawei P40',
        ]
        const chromeVersions = [
          '90.0.4430.210',
          '91.0.4472.120',
          '92.0.4515.159',
          '93.0.4577.82',
          '94.0.4606.61',
          '118.0.0.0',
        ]
        const androidVersion =
          androidVersions[Math.floor(Math.random() * androidVersions.length)]
        const phoneModel =
          phoneModels[Math.floor(Math.random() * phoneModels.length)]
        const chromeVersion =
          chromeVersions[Math.floor(Math.random() * chromeVersions.length)]
        return `Mozilla/5.0 (Linux; Android ${androidVersion}; ${phoneModel} Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${chromeVersion} Mobile Safari/537.36`
      }

      async function sendPostRequest() {
        const phoneInput = document.getElementById('phoneInput').value
        if (!validatePhone(phoneInput)) {
          alert('请输入有效的手机号码！')
          return
        }

        if (timer) {
          alert('请等待60秒后再尝试发送验证码')
          return
        }

        const formData = new FormData()
        formData.append('phone', phoneInput)
        formData.append('template', 'reg')

        try {
          // 定义请求头
          const axiosHeaders = {
            Accept: 'application/json, text/plain, */*',
            'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
            uid: 'undefined',
            'sec-ch-ua-mobile': '?1',
            'User-Agent': UA(),
            'sec-ch-ua-platform': 'Android',
            Origin: 'https://h5.qiekj.com',
            'X-Requested-With': 'mark.via',
            'Sec-Fetch-Site': 'same-site',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            Referer: 'https://h5.qiekj.com/',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
          }
          const response = await axios.post(API_SEND_CODE, formData, {
            headers: axiosHeaders,
          })
          if (response.data.code === 0) {
            alert('验证码发送成功！')
            startTimer()
          } else {
            alert('验证码发送失败：' + response.data.msg)
          }
        } catch (error) {
          console.error('请求失败:', error)
          alert('验证码发送失败！')
        }
      }

      function startTimer() {
        let countdown = 60
        const sendBtn = document.querySelector(
          "button[onclick='sendPostRequest()']"
        )
        sendBtn.disabled = true
        timer = setInterval(() => {
          if (countdown <= 0) {
            clearInterval(timer)
            timer = null
            sendBtn.textContent = '发送验证码'
            sendBtn.disabled = false
          } else {
            sendBtn.textContent = `重新发送(${countdown})`
            countdown--
          }
        }, 1000)
      }

      async function verifyCode() {
        const phoneInput = document.getElementById('phoneInput').value
        const verifyInput = document.getElementById('verifyInput').value

        const formData = new FormData()
        formData.append('channel', 'h5')
        formData.append('phone', phoneInput)
        formData.append('verify', verifyInput)

        const axiosHeaders = {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'multipart/form-data',
          Origin: 'https://h5.qiekj.com',
          Referer: 'https://h5.qiekj.com/',
          'User-Agent': UA(),
          'X-Requested-With': 'mark.via',
        }

        try {
          const response = await axios.post(API_USER_REG, formData, {
            headers: axiosHeaders,
          })
          if (response.data.code === 0) {
            document.getElementById('responseDisplay').textContent =
              response.data.data.token
            alert('登录成功！')
          } else {
            alert('登录失败：' + response.data.msg)
          }
        } catch (error) {
          console.error('登录失败:', error)
          alert('登录失败！')
        }
      }

      function copy() {
        const responseDisplay = document.getElementById('responseDisplay')
        navigator.clipboard
          .writeText(responseDisplay.textContent)
          .then(() => {
            alert('复制成功！')
          })
          .catch((err) => {
            console.error('复制失败:', err)
            alert('复制失败！')
          })
      }
    </script>
  </body>
</html>
